import { useRef, useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import React from "react";
import "./css/MXT2A.scss";
import {
  NavBar,
  Space,
  Form,
  Button,
  TextArea,
  Mask,
  SpinLoading,
  CheckList,
  Popup,
  SearchBar,
} from "antd-mobile";

import util from "./common/Util";
import constant from "./common/Constants";
function MXT2A() {
  const navigate = useNavigate();
  const formRef = useRef(null);
  const audioRef = useRef(null);
  const dataRef = useRef(null);

  const voiceItemConfig = {
    李老师: "narrator1",
    邓忞川: "AOT",
    青涩青年音色: "male-qn-qingse",
    精英青年音色: "male-qn-jingying",
    霸道青年音色: "male-qn-badao",
    青年大学生音色: "male-qn-daxuesheng",
    少女音色: "female-shaonv",
    御姐音色: "female-yujie",
    成熟女性音色: "female-chengshu",
    甜美女性音色: "female-tianmei",
    男性主持人: "presenter_male",
    女性主持人: "presenter_female",
    男性有声书1: "audiobook_male_1",
    男性有声书2: "audiobook_male_2",
    女性有声书1: "audiobook_female_1",
    女性有声书2: "audiobook_female_2",
    "青涩青年音色-beta": "male-qn-qingse-jingpin",
    "霸道青年音色-beta": "male-qn-badao-jingpin",
    "青年大学生音色-beta": "male-qn-daxuesheng-jingpin",
    "少女音色-beta": "female-shaonv-jingpin",
    "御姐音色-beta": "female-yujie-jingpin",
    "成熟女性音色-beta": "female-chengshu-jingpin",
    "甜美女性音色-beta": "female-tianmei-jingpin",
  };
  const items = Object.keys(voiceItemConfig);
  const [visible, setVisible] = useState(false);
  const [searchText, setSearchText] = useState("");
  const [selected, setSelected] = useState("李老师");
  const [showMask, setShowMask] = useState(false);

  const back = () => {
    navigate("/menuList");
  };
  const submit = (obj) => {
    setShowMask(true);
    const url = constant.baseUrl + "/app/mxT2a?token=" + util.getToken();

    fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(obj),
    })
      .then((response) => {
        let contentType = response.headers.get("Content-Type");
        if (contentType.indexOf("json") != -1) {
          return response.json();
        }
        return response.blob();
      })
      .then((ret) => {
        setShowMask(false);
        if (ret instanceof Blob) {
          dataRef.current = ret;
          console.info("返回成功:");
          audioRef.current.src = URL.createObjectURL(ret);
        } else if (ret instanceof Object) {
          console.info("返回错误", ret);
          if (ret.code === 50002) {
            localStorage.removeItem("token");
            navigate("/login");
          }
        }
      });
  };
  const reset = () => {
    formRef.current.resetFields();
    audioRef.current.src = "";
    const sel = "李老师";
    setSelected(sel);
    const voiceId = voiceItemConfig[sel];
    formRef.current.setFieldsValue({ voiceId });
    dataRef.current = null;
  };

  const filteredItems = (() => {
    if (searchText) {
      return items.filter((item) => item.includes(searchText));
    } else {
      return items;
    }
  })();
  const voiceIdSelect = (val) => {
    setSelected(val[0]);
    setVisible(false);
    const voiceId = voiceItemConfig[val[0]];
    formRef.current.setFieldsValue({ voiceId });
  };

  const download = () => {
    if (dataRef.current) {
      var url = window.URL.createObjectURL(dataRef.current);
      var a = document.createElement("a");
      a.href = url;
      a.download = "audio.mp3";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    }
  };

  useEffect(() => {
    const voiceId = voiceItemConfig[selected];
    formRef.current.setFieldsValue({ voiceId });
  }, []);

  return (
    <div className="MXT2A container">
      <NavBar onBack={back}>米麦语音合成</NavBar>
      <Form
        ref={formRef}
        onFinish={submit}
        style={{ "--prefix-width": "3.5em" }}
        layout="horizontal"
        footer={
          <div>
            <Space wrap block>
              <Button color="primary" type="submit">
                提交
              </Button>
              <Button onClick={reset}>重置</Button>
              <Button onClick={download} color="success">
                下载
              </Button>
            </Space>
          </div>
        }
      >
        <Form.Item
          name="text"
          label="文本"
          rules={[{ required: true }, { type: "string", min: 6 }]}
        >
          <TextArea
            placeholder="请输入合成文本"
            maxLength={200}
            rows={10}
            showCount
          />
        </Form.Item>
        <Form.Item name="voiceId" label="声音" rules={[{ required: true }]}>
          <div>
            {selected} <Button onClick={() => setVisible(true)}>选择</Button>
          </div>
        </Form.Item>
      </Form>

      <Space justify="start" block>
        <audio className="audio" controls ref={audioRef}></audio>
      </Space>

      <Popup
        bodyStyle={{ height: "60vh", overflow: "auto" }}
        visible={visible}
        onMaskClick={() => {
          setVisible(false);
        }}
        destroyOnClose
      >
        <div>
          <SearchBar
            placeholder="输入文字过滤选项"
            value={searchText}
            onChange={(v) => {
              setSearchText(v);
            }}
          />
        </div>
        <div>
          <CheckList onChange={voiceIdSelect}>
            {filteredItems.map((item) => {
              return (
                <CheckList.Item key={item} value={item}>
                  {item}
                </CheckList.Item>
              );
            })}
          </CheckList>
        </div>
      </Popup>
      <Mask visible={showMask}>
        <div className="mask">
          <SpinLoading style={{ "--size": "80px" }} />
        </div>
      </Mask>
    </div>
  );
}

export default MXT2A;
